package com.greatwqs.wmall.common.module.util;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import lombok.SneakyThrows;

import org.apache.commons.lang3.StringUtils;

import java.text.SimpleDateFormat;
import java.util.List;

/**
 * JsonUtil
 *
 * @author wang-qingsong
 * @since 2025/03/29
 */
public class JsonUtil {

    private static final ObjectMapper objectMapper = ObjectMapperUtil.objectMapper();

    /**
     * This method is just like "fromJson(String json, TypeReference<?> type)".
     * The purpose of this method is to make api looks more graceful.
     */
    @SneakyThrows
    public static <T> List<T> toList(String json, Class<T> innerType) {
        return objectMapper.readValue(json,
                objectMapper.getTypeFactory().constructCollectionType(List.class, innerType));
    }

    public static String toJson(Object obj) {
        return toJson(objectMapper, obj);
    }

    @SneakyThrows
    public static String toJson(ObjectMapper customObjectMapper, Object obj) {
        return customObjectMapper.writeValueAsString(obj);
    }

    @SneakyThrows
    public static <T> T fromJson(String json, TypeReference<T> type) {
        return objectMapper.readValue(json, type);
    }

    @SneakyThrows
    public static <T> T fromJson(String json, Class<T> clazz) {
        return objectMapper.readValue(json, clazz);
    }

    @SneakyThrows
    public static <T> T convertToObject(Object fromObject, Class<T> toClazz) {
        return objectMapper.convertValue(fromObject, toClazz);
    }

    public static <T> T convertToObject(Object fromObject, TypeReference<T> type) {
        return objectMapper.convertValue(fromObject, type);
    }
}
